//*********************************************************
//
//    Copyright (c) Microsoft. All rights reserved.
//    This code is licensed under the Apache License, Version 2.0.
//    THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
//    ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
//    IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
//    PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************

using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using Microsoft.Research.ScientificWorkflow.ManagementStudioControls.Common;
using Microsoft.Research.ScientificWorkflow.ManagementStudioControls.Interfaces;
using Microsoft.Research.ScientificWorkflow.UIDesigner.WpfComposite;
using Microsoft.Practices.Unity;
using System.Text;
using Microsoft.Research.ScientificWorkflow.TridentUtilities;

namespace Microsoft.Research.ScientificWorkflow.ManagementStudioControls
{
    /// <summary>
    /// The presentation model for the left pane.
    /// </summary>
    public class LeftPanePresenter : ILeftPaneNavigator
    {
        /// <summary>
        /// Unity container instance. 
        /// </summary>
        IUnityContainer container;

        /// <summary>
        /// A Key value pair consisting of the modules and their names.
        /// </summary>
        private Dictionary<string, ILeftPaneControl> leftPaneControls = new Dictionary<string, ILeftPaneControl>();
        
        /// <summary>
        /// The constructor for the leftpanepresenter.
        /// </summary>
        /// <param name="container"></param>
        /// <param name="view"></param>
        public LeftPanePresenter(LeftPaneView view, IUnityContainer container)
        {
            this.container = container;
            this.View = view;
            this.View.Presenter = this;
            this.InitializeCommands();
        }

        /// <summary>
        /// The View for the presentation model.
        /// </summary>
        public LeftPaneView View { get; set; }

        /// <summary>
        /// The current module selected.
        /// </summary>
        public ICommand ModuleSelected { get; set; }

        /// <summary>
        /// Select the default module to be shown at startup.
        /// </summary>
        public void SelectDefault()
        {
            this.ExecuteModuleSelected(ManagementStudioControlsConstants.WORKFLOWMANAGERSTRING);
        }

        /// <summary>
        /// Saves the changes across the modules.
        /// </summary>
        public SaveStateHandler SaveChanges()
        {
            SaveStateHandler saveState = new SaveStateHandler(SaveStatus.Valid);
            foreach (string key in this.leftPaneControls.Keys)
            {
                ILeftPaneControl leftPaneControl = this.leftPaneControls[key];
                if ((bool)leftPaneControl.Selector.IsChecked)
                {
                    saveState = leftPaneControl.SaveChanges();
                    break;
                }
            }

            return saveState;
        }

        /// <summary>
        /// Initialize the commands.
        /// </summary>
        private void InitializeCommands()
        {
            this.ModuleSelected = new DelegateCommand<string>(ExecuteModuleSelected);
        }

        /// <summary>
        /// Module selected command logic.
        /// </summary>
        /// <param name="jobString"></param>
        private void ExecuteModuleSelected(string jobString)
        {
            ILeftPaneControl selectedModule = this.leftPaneControls[jobString];
            if (selectedModule != null)
            {
                foreach (string key in this.leftPaneControls.Keys)
                {
                    if (!jobString.Equals(key, StringComparison.OrdinalIgnoreCase))
                    {
                        ILeftPaneControl leftPaneControl = this.leftPaneControls[key];
                        if ((bool)leftPaneControl.Selector.IsChecked)
                        {
                            SaveStateHandler saveStatus = leftPaneControl.SaveChanges();
                            if (SaveStatus.Invalid == saveStatus.SaveOptionSelected)
                            {
                                selectedModule.Selector.IsChecked = false;
                                return;
                            }
                        }

                        leftPaneControl.MainContent.Visibility = Visibility.Collapsed;
                        leftPaneControl.LeftPaneContent.Visibility = Visibility.Collapsed;
                        leftPaneControl.Selector.IsChecked = false;
                    }
                }

                selectedModule.MainContent.Visibility = Visibility.Visible;
                selectedModule.LeftPaneContent.Visibility = Visibility.Visible;
                selectedModule.Selector.IsChecked = true;
                StringBuilder titleBuilder = new StringBuilder(selectedModule.ObjectName);
                titleBuilder.Append(" - ");
                titleBuilder.Append(ManagementStudioResourceManager.GetString("ManagementStudioHeader"));
                this.container.Resolve<IRegionManager>("MainWindow").SetTitle(titleBuilder.ToString());
                this.container.Resolve<IStatusMessageControl>().SetText(string.Empty);
            }
        }

        #region ILeftPaneNavigator Members

        /// <summary>
        /// Adds a module into the left pane,
        /// </summary>
        /// <param name="leftPaneControl">The control to be added.</param>
        public void Add(string name, ILeftPaneControl leftPaneControl)
        {
            this.leftPaneControls.Add(name, leftPaneControl);

            this.View.LeftPaneContent.Children.Add(leftPaneControl.LeftPaneContent);

            ToggleButton moduleSelector = new ToggleButton();
            moduleSelector.Content = leftPaneControl.ObjectName;
            moduleSelector.Command = ModuleSelected;
            moduleSelector.CommandParameter = name;
            moduleSelector.Name = name + "_togBtn";

            Style buttonStyle = View.TryFindResource("ToggleButtonStyleLeft") as Style;
            moduleSelector.Style = buttonStyle;
            
            if (this.View.ButtonStack.Children.Count > 0)
            {
                moduleSelector.Margin = new Thickness(0, 5, 0, 0);
            }

            leftPaneControl.Selector = moduleSelector;
            
            this.View.ButtonStack.Children.Add(moduleSelector);
        }

        #endregion
    }
}
